<template>
    <div class="mapContent">
        <div id="map">
        </div>
    </div>
</template>

<script>
    import L from 'leaflet'
    import 'leaflet/dist/leaflet.css'
    import 'leaflet.chinatmsproviders'
    import omnivore from "@mapbox/leaflet-omnivore";

    export default {
        name: "kmlMap",
        props: ['kml'],
        data() {
            return {
                map: null
            }
        },
        mounted() {
            this.renderKmlMap(this.kml);
            this.map.invalidateSize(true);
        },
        watch: {
            kml: {
                handler (val) {
                    this.renderKmlMap(val);
                    this.map.invalidateSize(true);
                },
                deep:true
            }
        },
        methods: {
            renderKmlMap(kml) {
                if (this.map !== null) {
                    this.map.remove();
                }
                let normalM = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
                    maxZoom: 18,
                    minZoom: 5
                });
                let imgM = L.tileLayer.chinaProvider('GaoDe.Satellite.Map', {
                    maxZoom: 18,
                    minZoom: 5
                });
                let imgA = L.tileLayer.chinaProvider('GaoDe.Satellite.Annotion', {
                    maxZoom: 18,
                    minZoom: 5
                });

                let normal = L.layerGroup([normalM]),
                    image = L.layerGroup([imgM, imgA]);

                this.map = L.map("map", {
                    center: [31.59, 120.29],
                    zoom: 12,
                    layers: [normal],
                    zoomControl: false
                });

                let baseLayers = {
                    "地图": normal,
                    "影像": image,
                };

                L.control.layers(baseLayers, null).addTo(this.map);
                L.control.zoom({
                    zoomInTitle: '放大',
                    zoomOutTitle: '缩小'
                }).addTo(this.map);

                let customLayer = L.geoJson(null, {
                    style: function (feature) {
                        return {color: '#f00'};
                    }
                });
                let runLayer = omnivore.kml(kml, null, customLayer)
                    .on('ready', () => {
                        this.map.fitBounds(runLayer.getBounds());
                    })
                    .addTo(this.map)
            }
        }
    }
</script>

<style scoped lang="scss">
    .mapContent {
        width: 800px;
        height: 600px;
        overflow: hidden;
        position: relative;

        #map {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
        }
    }
</style>